﻿using System;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

namespace Business.DbConnect.Constant
{
    public class UserService
    {
        static QLNXeEntities entities = new QLNXeEntities();

        public static bool IsAdmin(short userId)
        {
            user user = entities.users.Find(userId);
            if (user != null)
            {
                if (RoleConstant.Admin.Equals(user.roleName.ToUpper()))
                {
                    return true;
                }
            }
            return false;
        }

        public static user ValidateUser(string userName, string passWord)
        {
            string pass = EncodePass(passWord);
            //SHA512 hash = new SHA512Managed();
            //return Convert.ToBase64String(hash.ComputeHash(Encoding.Unicode.GetBytes(str)));
            //var originalBytes = ASCIIEncoding.Default.GetBytes(passWord);
            return entities.users.FirstOrDefault(us => us.userName == userName && us.password == pass);
        }

        public static user GetUser(string userName)
        {
            return entities.users.FirstOrDefault(us => us.userName == userName);
        }

        public static bool ChangPass(string userName, string oldPass, string newPass)
        {
            user currentUser = ValidateUser(userName, oldPass);
            if (currentUser != null)
            {
                currentUser.password = EncodePass(newPass);
                entities.SaveChanges();
                return true;
            }
            return false;
        }

        public static string EncodePass(string originalPass)
        {
            var md5 = new MD5CryptoServiceProvider();
            return Convert.ToBase64String(md5.ComputeHash(Encoding.Unicode.GetBytes(originalPass)));
        }

        public static bool CheckClientAuthentication(String username, String rawPassword)
        {
            try
            {
                // encode pass to compare
                var encodedPass = EncodePass(rawPassword);
                var u = entities.users.FirstOrDefault(ob => ob.userName == username && ob.password == encodedPass);
                if (u == null)
                    return false;

                return RoleConstant.Admin.Equals(u.roleName, StringComparison.InvariantCultureIgnoreCase)
                    || RoleConstant.Member.Equals(u.roleName, StringComparison.InvariantCultureIgnoreCase);
            }
            catch
            {
                return false;
            }
        }
    }
}